<?php
/**
 * ajax交互
 */
defined('IN_TS') or die('Access Denied.');
switch($ts){
	case "new":
		
		break;
	//删除答案
	case "deleteAnswer":
		$commentid = intval($_POST['answerid']);
		$userid = aac('user') -> isLogin();
		
		//判断该答案的所有者
		$onecomment = $new['ask']->find('ask_comment', array('commentid'=>$commentid));
		if (($onecomment && $onecomment['userid'] == $userid) || 1 == $TS_USER['isadmin'])
		{
			$new['ask']->delete('ask_comment', array('commentid'=>$commentid));
			//计入答案数
			$new['ask']->reduce_ask_one($onecomment['askid']);
			//计入用户积分 减1分
			$new['ask']->reduce_userscore_one($userid);
			//查看回复操作记录表 是否有该回复相关的动作行为
			$lastestone = $new['ask']->find('ask_comment_op', array('commentid'=>$commentid), null, 'updatetime desc');
			if ($lastestone)
			{
				$pid = $lastestone['pid'];
				$askid = $onecomment['askid'];
				$f = $new['ask']->find('ask_topic', array('askid'=>$askid, 'pid'=>$pid, 'action'=>'ask_comment_op'));
				if ($f)
				{
					$new['ask']->update('ask_topic', array('askid'=>$askid), array('pid'=>0, 'action'=>''));
				}
			}
			$new['ask']->delete('ask_comment_op', array('commentid'=>$commentid));
		}
		echo 1;
		break;
	//编辑答案提交
	case "editAnswerPush":
		$commentid = intval($_POST['answerid']);
		$content = trim($_POST['content']);
		if ($content == '')
		{
			format_json(FAILURE, '没有任何内容是不允许你通过滴^_^');
		}
		if (mb_strlen($content, 'utf8') > 5000)
		{
			// 限制发表内容多长度，默认为5000
			format_json(FAILURE, '发这么多内容干啥^_^');
		}
		
		if (!$TS_USER['userid'])
		{
			format_json(FAILURE, '未登录');
		}
		$userid = $TS_USER['userid'];
		
		//判断该答案的所有者
		$onecomment = $new['ask']->find('ask_comment', array('commentid'=>$commentid));
		if ($onecomment && $onecomment['userid'] == $userid)
		{
			$f = $new['ask']->update('ask_comment',array('commentid'=>$commentid), array('comment'=>$content));
			if ($f)
			{
				format_json(SUCCESS, tsTitle($content));
			}
		}
		
		echo 0;
		break;
	//顶答案
	case "digg":
		$commentid = intval($_POST['answerid']);
		if (!$TS_USER['userid'])
		{
			format_json(FAILURE, '未登录');
		}
		$userid = $TS_USER['userid'];
		
		//不能顶自己的答案
		$onecomment = $new['ask']->find('ask_comment', array('commentid'=>$commentid));
		if ($onecomment)
		{
			if ($onecomment['userid'] == $userid)
			{
				format_json(FAILURE, '自己不可以评断自己的答案');
			}
		}
		
		//查找是否已经有过操作
		$onecommentop = $new['ask']->find('ask_comment_op', array('commentid'=>$commentid, 'userid'=>$userid));
		if ($onecommentop)
		{
			//10分钟之内只能支持/反对一次
			$now = time();
			if ($now - $onecommentop['updatetime'] < 600)
			{
				format_json(FAILURE, '10分钟之内只能支持/反对一次');
			}
			//顶过
			if ($onecommentop['type'] == 1)
			{
				format_json(FAILURE, '你已经支持过此答案');
			}
			
			//将反对记录置为支持记录
			$new['ask']->update('ask_comment_op', array('commentid'=>$commentid, 'userid'=>$userid), array('type'=>1, 'updatetime'=>$now));
			//更新回复顶字段数量
			$new['ask']->db->query("update ".dbprefix."ask_comment set digg = digg + 1,undigg = undigg - 1 where commentid = ".$commentid);
			//更新问题操作行为字段
			$new['ask']->update('ask_topic', array('askid'=>$onecomment['askid']), array(
					'action'=>'ask_comment_op',
					'pid'=>$onecommentop['pid'],
					'updatetime'=>time()
			));
			//计入用户积分
			$new['ask']->add_userscore_one($userid);
			
			//通知被顶者
			$msg_userid = '0';
			$msg_touserid = $onecomment['userid'];
			$msg_content = $TS_USER['username'].'支持了你的答案：'.t(tsDecode($onecomment['comment'])).'，快去看看吧^_^';

            $msg_url = tsUrl('ask','question',array('askid'=>$onecomment['askid']));

			aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_url);
			
			format_json(SUCCESS, array('userid'=>$userid, 'username'=>$TS_USER['username'], 'diggflag'=>true));
		}
		
		//插入新操作记录
		$pid = $new['ask']->create('ask_comment_op', array(
				    'commentid'=>$commentid,
				    'userid'=>$userid,
				    'type'=>1,
				    'updatetime'=>time()
				));
		//更新回复顶字段数量
		$new['ask']->add_comment_one($commentid);
		//更新问题操作行为字段
		$new['ask']->update('ask_topic', array('askid'=>$onecomment['askid']), array(
				    'action'=>'ask_comment_op',
				    'pid'=>$pid,
				    'updatetime'=>time()
				));
		//计入用户积分
		$new['ask']->add_userscore_one($userid);
		
		//通知被顶者
		$msg_userid = '0';
		$msg_touserid = $onecomment['userid'];
		$msg_content = $TS_USER['username'].'支持了你的答案：'.t(tsDecode($onecomment['comment'])).'，快去看看吧^_^ ';

        $msg_url = tsUrl('ask','question',array('id'=>$onecomment['askid']));

		aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_url);
		
		format_json(SUCCESS, array('userid'=>$userid, 'username'=>$TS_USER['username'], 'diggflag'=>false));
		break;
	case "undigg":
		$commentid = intval($_POST['answerid']);
		$userid = aac('user') -> isLogin();
		
		//不能顶自己的答案
		$onecomment = $new['ask']->find('ask_comment', array('commentid'=>$commentid));
		if ($onecomment)
		{
			if ($onecomment['userid'] == $userid)
			{
				tsNotice('自己不可以评断自己的答案^_^');
			}
		}
		
		//查找是否已经有过操作
		$onecommentop = $new['ask']->find('ask_comment_op', array('commentid'=>$commentid, 'userid'=>$userid));
		if ($onecommentop)
		{
			//10分钟之内只能支持/反对一次
			$now = time();
			if ($now - $onecommentop['updatetime'] < 600)
			{
				format_json(FAILURE, '10分钟之内只能支持/反对一次');
			}
			//踩过
			if ($onecommentop['type'] == 0)
			{
				format_json(FAILURE, '你已经反对过此答案');
			}
				
			//将支持记录置为反对记录
			$new['ask']->update('ask_comment_op', array('commentid'=>$commentid, 'userid'=>$userid), array('type'=>0, 'updatetime'=>$now));
			//更新回复反对字段数量
			$new['ask']->db->query("update ".dbprefix."ask_comment set digg = digg - 1,undigg = undigg + 1 where commentid = ".$commentid);
			//计入用户积分 减1分
			$new['ask']->reduce_userscore_one($userid);
			
			format_json(SUCCESS, array('userid'=>$userid, 'username'=>$TS_USER['username'], 'diggflag'=>true));
		}
		
		//插入新操作记录
		$pid = $new['ask']->create('ask_comment_op', array(
				'commentid'=>$commentid,
				'userid'=>$userid,
				'type'=>0,
				'updatetime'=>time()
		));
		//更新回复顶字段数量
		$new['ask']->opp_comment_one($commentid);
		//计入用户积分 减1分
		$new['ask']->reduce_userscore_one($userid);
		
		format_json(SUCCESS, array('userid'=>$userid, 'username'=>$TS_USER['username'], 'diggflag'=>false));
		break;
	case "closeOrOpenQuestion":
		$askid = intval($_POST['askid']);
		$userid = aac('user') -> isLogin();
		
		//判断问题所有者
		$askarr = $new['ask']->find('ask_topic', array('askid'=>$askid));
		if (!$askarr)
		{
			format_json(FAILURE, '该问题不存在或已被删除');
		}
		if ($askarr['userid'] != $userid)
		{
			format_json(FAILURE, '无权编辑该问题');
		}
		$now = time();
		if ($now - $askarr['opentime'] < 600)
		{
			format_json(FAILURE, '问题10分钟内只可以打开/关闭1次');
		}
		
		$isopen = 0;
		if (0 == $askarr['isopen'])
		{
			$isopen = 1;
		}
		$new['ask']->update('ask_topic', array('askid'=>$askid), array(
				'isopen'=>$isopen,
				'opentime'=>$now
		));
		format_json(SUCCESS, array());
		break;
	case "follow":
		$cateid = intval($_POST['cateid']);
		$userid = aac('user') -> isLogin();
		
		$catearr = $new['ask']->find("ask_user_cate", array('userid'=>$userid, 'cateid'=>$cateid));
		if ($catearr)
		{
			//有存在记录 此时属于取消关注 删除该记录
			$new['ask']->delete("ask_user_cate", array('userid'=>$userid, 'cateid'=>$cateid));
			echo 1;
			return;
		}
		
		//未关注 插入新记录
		$new['ask']->create("ask_user_cate", array('userid'=>$userid, 'cateid'=>$cateid, 'addtime'=>time()));
		echo 1;
		break;
	case "expandAnswer":
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$orderby = $_POST['orderby'];
		$askid = intval($_POST['askid']);
		
		//分页处理
		$start = COMMENT_PAGE_NUM * ($page - 1);
		
		//回复列表
		$orderflag = '';
		$orderby = ' order by digg - undigg desc,a.addtime asc';
		if ($orderby == 'date')
		{
			$orderby = ' order by a.addtime asc';
			$orderflag = 'date';
		}
		$sql = "select a.commentid,a.comment,a.digg,a.undigg,a.addtime,b.userid,b.username,b.face,b.path from ".dbprefix."ask_comment a left join ".dbprefix."user_info b on a.userid=b.userid where a.askid =".$askid.$orderby;
		$commentarr = $new['ask']->db->fetch_all_assoc($sql." limit $start,".COMMENT_PAGE_NUM);
		//总数
		$commentNum = $new['ask']->db->once_num_rows($sql);
		
		//遍历答案
		foreach ($commentarr as $key=>$v)
		{
			$diggarr = array();
			$oparr = $new['ask']->findall('ask_comment_op', array('commentid'=>$v['commentid']), 'updatetime desc');
			$i = 0;
			foreach ($oparr as $k=>$value)
			{
				if ($value['type'] == 1)
				{
					$tempuser = aac('user')->getOneUser($value['userid']);
					$diggarr[$i]['userid'] = $tempuser['userid'];
					$diggarr[$i]['username'] = $tempuser['username'];
					$i++;
				}
			}
		
			$commentarr[$key]['diggarr'] = $diggarr;
		}
		
		//分页 上一页和下一页
		$next = 0;
		if (($page+1)<= ceil($commentNum/COMMENT_PAGE_NUM))
		{
			$next = $page+1;
		}
		
		include template('comment_more');
		break;
	case "addcomment":
		$content = trim($_POST['content']);
		$dataid = $_POST['dataid'];
		$datatype = $_POST['datatype'];
		
		if (!$TS_USER['userid'])
		{
			format_json(FAILURE, '未登录');
		}
		if (mb_strlen($content, 'utf8') > 500)
		{
			// 限制发表内容多长度，默认为500
			format_json(FAILURE, '最多允许输入500字');
		}
		
		$userid = $TS_USER['userid'];
		if ('question' == $datatype)
		{
			$addcommentarr = $new['ask']->find('ask_question_add', array('userid'=>$userid, 'askid'=>$dataid), null, 'addtime desc');
			$now = time();

            /*
			if ($addcommentarr)
			{
				if ($now - $addcommentarr['addtime'] < 600)
				{
					format_json(FAILURE, '10分钟之内只能添加一次讨论');
				}
			}
            */

			$replyid = $new['ask']->create('ask_question_add', array(
					    'askid'=>$dataid,
					    'userid'=>$userid,
					    'content'=>$content,
					    'addtime'=>$now
					));
			$retundata = array();
			if ($replyid)
			{
				$home_url = tsUrl('user','space',array('id'=>$userid));
				$retundata = array(
						    'userid'=>$userid,
						    'username'=>$TS_USER['username'],
						    'home_url'=>$home_url,
						    'replyid'=>$replyid,
						    'content'=>tsTitle($content),
						    'addtime'=>date('Y-m-d', $now)
						);
				
				//通知问题发起者
				$onecomment = $new['ask']->find('ask_topic', array('askid'=>$dataid));
				if ($userid != $onecomment['userid'])
				{
					$msg_userid = '0';
					$msg_touserid = $onecomment['userid'];
					$msg_content = $TS_USER['username'].'对你的问题添加了讨论：'.t(tsDecode($content)).'，快去看看吧^_^ ';

                    $msg_url = tsUrl('ask','question',array('id'=>$dataid));

					aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_url);
				}
			}
			
			format_json(SUCCESS, $retundata);
		}
		if ('answer' == $datatype)
		{
			$addcommentarr = $new['ask']->find('ask_comment_add', array('userid'=>$userid, 'commentid'=>$dataid), null, 'addtime desc');
			$now = time();
			if ($addcommentarr)
			{
				if ($now - $addcommentarr['addtime'] < 600)
				{
					format_json(FAILURE, '10分钟之内只能添加一次讨论');
				}
			}	
			
			$replyid = $new['ask']->create('ask_comment_add', array(
					'commentid'=>$dataid,
					'userid'=>$userid,
					'content'=>$content,
					'addtime'=>$now
			));
			$retundata = array();
			if ($replyid)
			{
				$home_url = tsUrl('user','space',array('id'=>$userid));
				$retundata = array(
						'userid'=>$userid,
						'username'=>$TS_USER['username'],
						'home_url'=>$home_url,
						'replyid'=>$replyid,
						'content'=>tsTitle($content),
						'addtime'=>date('Y-m-d', $now)
				);
				
				//通知问题发起者
				$onecomment = $new['ask']->find('ask_comment', array('commentid'=>$dataid));
				if ($userid != $onecomment['userid'])
				{
					$msg_userid = '0';
					$msg_touserid = $onecomment['userid'];
					$msg_content = $TS_USER['username'].'对你的答案添加了讨论：'.t(tsDecode($content)).'，快去看看吧^_^ ';

                    $msg_url = tsUrl('ask','question',array('id'=>$onecomment['askid']));

					aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_url);
				}
			}
				
			format_json(SUCCESS, $retundata);
		}
		break;
	case "deladdcomment":
		$dataid = intval($_POST['dataid']);
		$datatype = $_POST['datatype'];
		
		if (!$TS_USER['userid'])
		{
			format_json(FAILURE, '未登录');
		}
		$userid = $TS_USER['userid'];
		if ('question' == $datatype)
		{
			//判断讨论的所有者
			$addcommentarr = $new['ask']->find('ask_question_add', array('replyid'=>$dataid));
			if ($addcommentarr)
			{
				if ($addcommentarr['userid'] == $userid)
				{
					$new['ask']->delete('ask_question_add', array('replyid'=>$dataid));
					format_json(SUCCESS);
				}
			}
		}
		if ('answer' == $datatype)
		{
			//判断讨论的所有者
			$addcommentarr = $new['ask']->find('ask_comment_add', array('replyid'=>$dataid));
			if ($addcommentarr)
			{
				if ($addcommentarr['userid'] == $userid)
				{
					$new['ask']->delete('ask_comment_add', array('replyid'=>$dataid));
					format_json(SUCCESS);
				}
			}
		}
		break;
}

//生成json数据
function format_json($code=0,$html='')
{
	echo json_encode(array('code'=>$code, 'html'=>$html));
	exit();
}